/*
 * @Author: 快的
 * @Description: 出码工具自动生成，不允许修改此部分注释
 * @pageUuid: 3421d639-67fc-4165-b308-265cce51c90e
 * @file: nkfe.shouquanguanli/app/src/nodes/person-list-manage/manageDrawer.tsx
 */
import React, { useState, useEffect, useRef } from 'react';
import { Drawer, Tag, Input, Loading, notification } from '@ss/mtd-react';
import { Button, Form, Select, AsyncButton } from '@block/plug';
import M from '@block/utils';
import { PersonListDetail } from '../../type';
import URL from '../../url';
import './DetailDrawer.scss';

/** Props 声明 */
interface Props {
  /** 人员名单id */
  personListId: number;
  /** 侧滑状态标志 */
  drawerMode: Mode;
  /** 关闭弹窗方法 */
  setManageDrawerVisible: React.Dispatch<React.SetStateAction<boolean>>;
  /** 搜索列表刷新方法 */
  recordsSearch: () => void;
  /** 更新tab角标数据方法 */
  getStatusCount: () => void;
}

/**
 * 名单管理详情侧滑
 */
const ManageDrawer = (props: Props) => {
  const { personListId, drawerMode, setManageDrawerVisible, recordsSearch, getStatusCount } = props;

  /** state 定义 */
  const [loading, setLoading] = useState<boolean>(true); // 侧滑loading状态位

  /** ref 定义 */
  const ManageFormRef = useRef<Form>(null); // 名单详情ref实例

  /** 获取侧滑详情数据 */
  const ManageFormInitData = async () => {
    setLoading(true);
    try {
      const res = await M.$fetch<PersonListDetail>(URL.viewPersonList, { personListId });
      ManageFormRef.current?.setFieldsValue(res);
    } finally {
      setLoading(false);
    }
  };

  /** DidMount */
  useEffect(() => {
    ManageFormInitData();
  }, []);

  /**
   * 编辑态的修改保存处理
   * @param e event
   * @param btn 按钮实例
   */
  const handleSave = async (e: MouseEvent, btn: Button) => {
    if (ManageFormRef.current.validateFields()) {
      const formData = ManageFormRef.current?.getFieldsValue();
      const sensitivePosTypeList = formData.sensitivePosTypeList?.map((item) => item?.code);
      const params = { personListId, sensitivePosTypeList, riskDesc: formData?.riskDesc };
      btn.loading(true);
      try {
        const res = await M.$fetch<OperateResponse>(URL.modifyPersonList, params);
        notification.success({ title: '成功', message: res?.message || '操作成功' });
        recordsSearch();
        getStatusCount();
        setManageDrawerVisible(false);
      } finally {
        btn.loading(false);
      }
    }
  };

  return (
    <div style={{ height: '600px' }}>
      <Drawer
        title={
          <div className="person-manage-detail-drawer-title">
            <div className="header-title">人员详情</div>
            {drawerMode === 'edit' && (
              <div className="header-btns">
                <Button onClick={() => setManageDrawerVisible(false)}>取消</Button>
                <AsyncButton type="primary" onClick={handleSave}>
                  保存
                </AsyncButton>
              </div>
            )}
          </div>
        }
        width={600}
        visible
        onClose={() => setManageDrawerVisible(false)}
      >
        <Loading loading={loading}>
          <Form mode={drawerMode} ref={ManageFormRef} labelWidth="120px" labelPosition="right" labelInValue={false}>
            <Form.Item formItemKey="personListStatusName" label="状态：" span={24}>
              {(e) => <Tag>{e.parentForm.getFieldsValueIncludeHide().personListStatusName}</Tag>}
            </Form.Item>
            <Form.Item formItemKey="createTypeName" label="创建类型：" span={24}>
              {(e) => <span>{e.value}</span>}
            </Form.Item>
            <Form.Item formItemKey="createSourceName" label="创建源：" span={24}>
              {(e) => <span>{e.value}</span>}
            </Form.Item>
            <Form.Item formItemKey="empName" label="人员：" span={24}>
              {(e) => <span>{e.value}</span>}
            </Form.Item>
            <Form.Item formItemKey="orgNamePath" label="所在组织：" span={24}>
              {(e) => <span>{e.value}</span>}
            </Form.Item>
            <Form.Item formItemKey="jobFamilyName" label="JobFamily：" span={24}>
              {(e) => <span>{e.value}</span>}
            </Form.Item>
            <Form.Item formItemKey="jobGroupName" label="JobGroup：" span={24}>
              {(e) => <span>{e.value}</span>}
            </Form.Item>
            <Form.Item formItemKey="joinDate" label="入职时间：" span={24}>
              {(e) => <span>{M.datejs(e.value).format('YYYY-MM-DD')}</span>}
            </Form.Item>
            <Form.Item formItemKey="level" label="职级：" span={24}>
              {(e) => <span>{e.value}</span>}
            </Form.Item>
            <Form.Item formItemKey="subordinateCount" label="下属人数：" span={24}>
              {(e) => <span>{e.value}</span>}
            </Form.Item>
            <Form.Item
              formItemKey="sensitivePosTypeList"
              label="敏感岗位分类："
              required
              message="请填写必填项"
              span={24}
            >
              <Select
                keyField="code"
                labelField="name"
                multiple
                filterable={false}
                onFetchData={() => M.$fetch<SelectOption<string>[]>(URL.querySensitivePosTypeList)}
                toFormItem
              />
            </Form.Item>
            <Form.Item formItemKey="riskDesc" label="风险描述：" span={24}>
              <Input.TextArea
                showCount
                placeholder="请输入纳入敏感岗位管理的原因，如该岗位风险等"
                toFormItem
                maxLength="500"
              />
            </Form.Item>
          </Form>
        </Loading>
      </Drawer>
    </div>
  );
};

export default ManageDrawer;
